package controller;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


import CRUD.MemberHome;
import CRUD.MessageHome;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import xmlMapping.Member;
import xmlMapping.Message;

/**
 *
 * @author labib
 */
public class sendMesg extends org.apache.struts.action.Action {
    
    /* forward name="success" path="" */
    private static final String SUCCESS = "success";
    
    /**
     * This is the action called from the Struts framework.
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        ActionErrors errors = new ActionErrors();
       String dest= request.getParameter("dest");
       String title= request.getParameter("title");
       String msgBody= request.getParameter("body");
     
        
     
        System.out.println(" body "+msgBody);
        System.out.println();
        System.out.println(" title "+title);
        System.out.println();
        System.out.println(" dest is "+dest);
        
        Message msend=new Message();
        
        msend.setBody(msgBody);
        msend.setDate(new Date());
        msend.setTitle(title);
        
        
        
        Member membersend=new Member();
        
        
        
        /// we must get ID of that person that want to send msg   method must be implemented (name of memebr and get that )
       Integer id= (Integer) request.getSession(false).getAttribute("id");
        membersend.setMemberId(id);
        
        // set as sender of mesage
        msend.setMemberBySenderId(membersend);
         Member membrdest;
        try{
        /// must get member destination 
         membrdest=new MemberHome().findByUserName(dest);
        
     
        membrdest.setMemberId(membrdest.getMemberId());
        
        
        msend.setMemberByMemberId(membrdest);
        MessageHome hom=new MessageHome();
        hom.persist(msend);
        }
          catch(Exception c)
        {
                 errors.add("userName", new ActionMessage("DestinationError"));


                saveErrors(request, errors);

                return mapping.findForward("error");
        }
        
        
        return mapping.findForward("myMessages");
    }
}
